package com.tanx.cqrs.infrastructure.spring.event.handler;

import com.tanx.cqrs.event.Event;
import com.tanx.cqrs.event.EventBus;
import com.tanx.cqrs.infrastructure.spring.event.EventProxy;
import com.tanx.cqrs.event.store.EventStoreRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 处理历史事件
 */
public class EventHistoryHandler {

    private ApplicationContext context;
    private EventBus eventBus;

    private Collection<EventStoreRepository> beans;

    public EventHistoryHandler(ApplicationContext context, EventBus eventBus) {
        this.context = context;
        this.eventBus = eventBus;
    }

    @Scheduled(fixedRate = 5000)
    public void handler() {
        List<List<Event>> list = new ArrayList<>(beans.size());
        for (EventStoreRepository bean : beans) {
            List<Event> events = bean.findByUnFinishEventByCreateDateTimeAsc();
            list.add(events);
        }
        list.parallelStream().forEach(eventProxies -> {
            for (Event eventProxy : eventProxies) {
                eventBus.invokeHandler(eventProxy);
                eventBus.eventFinish(eventProxy);
            }
        });
    }

    public void registerAllHandler() {
        Map<String, EventStoreRepository> beans = context.getBeansOfType(EventStoreRepository.class);
        this.beans = beans.values();
    }
}
